package com.axonactive.yolo.service.implement;

import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.axonactive.yolo.dao.interfaces.TaskRepository;
import com.axonactive.yolo.domain.Task;
import com.axonactive.yolo.exception.TaskNotFoundException;
import com.axonactive.yolo.service.interfaces.TaskService;

@Service
public class TaskServiceImpl implements TaskService {
	
	private final static Logger LOGGER = Logger.getLogger(TaskServiceImpl.class);

	@Resource
	private TaskRepository taskRepository;

	@Transactional
	public List<Task> findAll() {
		return taskRepository.findAll();
	}

	@Transactional
	public Task create(Task task) {
		return taskRepository.save(task);
	}

	@Transactional(rollbackFor = TaskNotFoundException.class)
	public boolean delete(int id) throws TaskNotFoundException {
		Task deletedTask = taskRepository.findOne(id);

		if (deletedTask == null) {
			return false;
		}
		taskRepository.delete(deletedTask);
		return true;
	}

	@Transactional(rollbackFor = TaskNotFoundException.class)
	public boolean update(Task task) throws TaskNotFoundException {
		if (task.getId() == 0) {
			create(task);
			return true;
		}
		
		Task updatedTask = taskRepository.findOne(task.getId());
		if (updatedTask == null){
			return false;
		}
		updatedTask.setTypeOfTrip(task.getTypeOfTrip());
		updatedTask.setFromCode(task.getFromCode());
		updatedTask.setToCode(task.getToCode());
		updatedTask.setFromAirport(task.getFromAirport());
		updatedTask.setToAirport(task.getToAirport());
		updatedTask.setFromCountry(task.getFromCountry());
		updatedTask.setToCountry(task.getToCountry());
		updatedTask.setDepartDate(task.getDepartDate());
		updatedTask.setReturnDate(task.getReturnDate());
		updatedTask.setCabinClass(task.getCabinClass());
		updatedTask.setTaskId(task.getTaskId());
		updatedTask.setAvailable(task.getAvailable());

		taskRepository.save(updatedTask);

		return true;
	}

	@Override
	public Task findByTaskId(String taskId) {
		if (taskRepository.findByTaskId(taskId).size() == 0) {
			return null;
		}
		
		return taskRepository.findByTaskId(taskId).get(0);
	}

	@Override
	public List<Task> findByAvailable(String available) {
		return taskRepository.findByAvailable(available);
	}

	@Override
	public Task findById(int id) {
		return taskRepository.findOne(id);
	}

}
